package org.andengine.bulletml.simple;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.simpleframework.xml.*;

@Root (name = "sequence")
public class ActionSeq implements ActBasics{
	
	@Attribute (required = true)
	private String label;	
	
	@ElementMap (entry ="entry", key="label", attribute=true, required = true, inline=true)
	private Map<String, Action> actions;

	@Element (required = true, name = "order")
	private String execOrder = ""; //comma separated

	@Element (required = false)
	private int repeat = 0;
	
	@Element (required = true, name = "recovery")
	private float recoveryInt = 0.0f;
	
	@Element (required = false, name = "augment")
	private String buff = "";
	
	public float timer = 0;
	
	private LinkedList<String> actQueue = new LinkedList<String>();
	
	private LinkedList<Action> current = new LinkedList<Action>();
	
	public boolean active = false;
	public boolean isSeq = true;

	public int getRepeat() {
		return repeat;
	}

	public float getRecovery() {
		return recoveryInt;
	}

	public Map<String, Action> getActions() {
		return actions;
	}
	
	public void compileQ(){
		for(String str: execOrder.split(",")){
			actQueue.offer(str);
		}
	}
	
	public boolean nextActions(){
		if(execOrder.length() == 0 || actQueue.isEmpty()){
			return false;
		}
					
		String temp = actQueue.poll();
		LinkedList<Action> tList = new LinkedList<Action>();
		
		if(temp.contains("+")){
			for(String s: temp.split("+"))
				tList.add(actions.get(s));
		}
		this.current = tList;
		return true;
	}

	public float calcTotalActTime(){
		float actTime = 0;
		for(String temp : this.actQueue){
			if(temp.contains("+")){
				for(String s: temp.split("+"))
					actTime += actions.get(s).getFiringInt();
			}
			else
				actTime += actions.get(temp).getFiringInt();
		}
		return actTime;
	}
	
	public LinkedList<Action> getCurrentActions() {
		return current;
	}
	
	public boolean hasNextSet(){
		return !actQueue.isEmpty();
	}

	@Override
	public int compareTo(Action arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int compareTo(ActionSeq arg0) {
		// TODO Auto-generated method stub
		int result = Math.round(this.recoveryInt) - Math.round(arg0.recoveryInt);
		if(result == 0) 
			result+= Math.round(this.calcTotalActTime()*this.repeat) - Math.round(arg0.calcTotalActTime()*arg0.repeat);
		if(result == 0)
			result+= this.actQueue.size() - arg0.actQueue.size();
		return result;
	}

	public String getBuff() {
		return buff;
	}

	public String getLabel() {
		return label;
	}

}
